package com.tencent.wxcloudrun;

import com.tencent.wxcloudrun.response.AppException;
import com.tencent.wxcloudrun.response.ErrorCodeMsgEnum;
import com.tencent.wxcloudrun.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.tencent.wxcloudrun
 * Description:
 *
 * @Date: 2023/1/22 9:00 AM
 * @Author: wht
 */
@Slf4j
@ControllerAdvice
// 加了@ControllerAdvice这个之后，springboot碰到抛出异常就会自动执行这个类里的exceptionHandler方法
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public <T> R<T> exceptionHandler(Exception e) {
        //这里先判断拦截到的Exception是不是我们自定义的异常类型
        if (e instanceof AppException) {
            AppException appException = (AppException) e;
            return R.error(appException.getErrorCodeMsgEnum());
        } else {
            log.error("500", e);
            //如果拦截的异常不是我们自定义的异常(例如：数据库主键冲突)
            return R.error(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }
}
